package com.xnew.encrypt;

import com.xnew.constant.Constant;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.io.UnsupportedEncodingException;

public class Sm3Encrypt {
	/**
	 * 生成随机32位盐值
	 * */
	public static String getSaltString(){
		RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
		return randomNumberGenerator.nextBytes().toHex();
	}
	
	/**
	 * 使用sm3进行密码加密
	 * */
	public static String encrypt(String key){
		byte[] data;
		try {
			data = key.getBytes("UTF-8");
			byte[] returnHash = hash(data);
			return ByteUtils.toHexString(returnHash);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 使用sm3进行密码加密
	 * */
	public static String encrypt(String salt, String key, String userName){
		return encrypt(salt+key+userName);
	}

	/**
	 * 返回长度=32的byte数组
	 * @explain 生成对应的hash值
	 * @param data
	 * @return
	 */
	public static byte[] hash(byte[] data) {
	    SM3Digest digest = new SM3Digest();
	    digest.update(data, 0, data.length);
	    byte[] hash = new byte[digest.getDigestSize()];
	    digest.doFinal(hash, 0);
	    return hash;
	}
	public static void main(String[] args){
		String salt = getSaltString();
		System.out.println(salt);
		System.out.println(encrypt(salt, Constant.SET_PASSWD,"临时测试用户01"));
	}
}
